<template>
  <div v-loading="statusLoading">
    <attach-upload
      :tags="uploadTags"
      :batch-no="relatedId"
      :view-mode="isView"
      v-bind="$listeners"
      ref="upload"
      @after-data="handleAfterData"
    >
      <template slot="application">
        <attach-application
          :project-data="projectData"
          :sign-data="signData"
          :tag="applicationTag"
          :view-mode="isView"
          @after-data="handleAfterData"
          @type-change="handleSignTypeChange"
        ></attach-application>
      </template>
    </attach-upload>
  </div>
</template>

<script>
import {
  enumPersonalTags,
  enumCompanyTags,
  applicationSlot,
} from '@/credit/views/city/bus/normal/item/attach'

import AttachUpload from '@/bank/components/attach/Upload'
import AttachApplication from '@/credit/views/city/bus/normal/item/AttachApplication'

export default {
  components: {
    AttachUpload,
    AttachApplication,
  },
  props: {
    viewMode: Boolean,
    relatedId: String,
  },
  data() {
    return {
      loading: false,
      statusLoading: false,
      lastFetchId: '',
      projectData: {},
      signData: {},
      attachs: [],
      isOnlineSign: 0,
    }
  },
  computed: {
    isCompany() {
      return +this.projectData.customer_type === 1
    },
    uploadTags() {
      return this.isCompany ? enumCompanyTags : enumPersonalTags
    },
    applicationTag() {
      const tag = this.uploadTags.find(it => it.slot === applicationSlot) || {}
      return {
        tag: tag.tag,
        parentTag: tag.parentTag,
        required: tag.required,
      }
    },
    isView() {
      return this.viewMode
    },
    signStatus() {
      return +(this.signData.sign_status || 0)
    },
  },
  watch: {
    relatedId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    beforeClose() {
      this.$emit('update:visible', false)
    },
    getData() {
      if (!this.relatedId || (this.loading && this.relatedId === this.lastFetchId)) return
      this.lastFetchId = this.relatedId
      this.loading = true
      return Promise.all([this.getRelatedData(), this.getSignData()]).finally(() => {
        this.loading = false
      })
    },
    getRelatedData() {
      this.$api
        .getData({
          table: 'customer_related',
          params: {
            'customer_related_id.eq': this.relatedId,
          },
        })
        .then(res => {
          this.projectData = res?.data?.[0] ?? {}
          this.isOnlineSign = +(this.projectData.is_online_sign || 0)
        })
        .finally(() => {
          // 主动调用时，重置附件（父级visible改变后更新附件）
          this.$refs.upload?.init()
        })
    },
    getSignData() {
      return this.$api
        .getData({
          table: 'customer_apply_sign',
          params: {
            'sign_type.eq': 1,
            'customer_related_id.eq': this.relatedId,
          },
        })
        .then(res => {
          this.signData = res?.data?.[0] ?? {}
        })
    },
    handleSignTypeChange(status) {
      this.isOnlineSign = +status
      this.getData().then(() => this.updateStatus())
    },

    handleAfterData({ list, emit }) {
      if (emit) {
        this.$emit('success', list)
      }
      if (this.isView) return
      this.attachs = list
      this.updateStatus()
    },
    updateStatus() {
      // 判断附件状态
      const listObj = this.attachs.reduce((prev, curr) => {
        const tag = curr.attachment_type
        if (!prev[tag]) prev[tag] = []
        prev[tag].push(curr)
        return prev
      }, {})
      const isAllUpload = this.uploadTags.every(tag => {
        if (tag.slot === applicationSlot && this.isOnlineSign === 1) {
          return this.signStatus >= 2
        }
        if (!tag.required) return true
        const atts = listObj[tag.tag]
        return atts && atts.length > 0
      })
      const currentStatus = isAllUpload ? 1 : 0
      this.$emit('status', currentStatus)
    },
  },
}
</script>

<style lang="scss" scoped>
.attach-title {
  font-size: 1.1rem;
  font-weight: bold;
}
</style>
